import React, { useEffect } from 'react';
import { connect } from 'umi';
import moment from 'moment';
import { eventTrack } from '@/utils/track';
import { Form, Table, Card, Button, Input, DatePicker } from 'antd';
import { utils } from 'vv-frontend-components';
import LinkTo from '@/components/LinkTo';
import isEmpty from 'lodash/isEmpty';
import { history } from 'umi';
// import { adjustPostState } from '@/utils/adjustPostState';
// AuthComponent AuthCode权限控制
// import AuthCode from '@/utils/auth/AuthCode';
import AuthComponent from '@/utils/auth/AuthComponent';
import CompanyDepart from '@/components/CompanyDepart';
import PageRouter from '@/components/PageRouter/PageRouter';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Pagination from '@/components/Pagination';
import styles from './index.less';

const { RangePicker } = DatePicker;
const Resigned = ({ form, loading, resigned, dispatch, location }) => {
    // 按钮权限控制
    // const { authCode } = new AuthCode(route.code);
    // 过滤高级搜索空格
    const { deepTrim } = utils;
    const { query } = location;
    const { pagination, data } = resigned;
    // 获取登陆人公司id
    // 获取参数
    const { getFieldsValue } = form;
    const { getFieldDecorator } = form;
    // 获取查询参数
    const getSearchData = pageNo => {
        // 方法自动获取高级搜索表单参数
        const { userName, companyDepart, changeDateSearch } = getFieldsValue();
        // 接口传参参数
        const payload = {
            pageNo: pageNo || pagination.current,
            pageSize: pagination.pageSize,
            // 高级搜索字段
            employeeName: userName || '',
            companyId: companyDepart.companyId || '',
            departmentId: companyDepart.departmentId || '',
            startActualLeaveDate:
                !isEmpty(changeDateSearch) && changeDateSearch[0] ? changeDateSearch[0].format('YYYY-MM-DD') : '',
            endActualLeaveDate:
                !isEmpty(changeDateSearch) && changeDateSearch[1] ? changeDateSearch[1].format('YYYY-MM-DD') : ''
        };
        return payload;
    };
    // 接口请求
    const fetchList = (ctx = {}) => {
        const { pageNo = null } = ctx;
        dispatch(
            deepTrim({
                type: 'resigned/fetchList',
                payload: {
                    ...getSearchData(pageNo)
                }
            })
        );
    };
    const renderDetail = record => {
        if (record.assigneeEmployeeNames !== '') {
            // 跳转到旧流程
            return (
                <LinkTo
                    to="/office/personnelManagement/onboardAndLeave/applyLeave"
                    query={{
                        leaveOfficeId: record.id,
                        type: 'company'
                    }}
                >
                    详情
                </LinkTo>
            );
        }
        return (
            <LinkTo
                to="/office/personnelManagement/onboardAndLeave/oldApplyLeave"
                query={{
                    processInstanceId: record.processInstanceId
                }}
            >
                详情
            </LinkTo>
        );
    };
    // 列表项
    const columns = [
        {
            title: '姓名',
            dataIndex: 'employeeName',
            key: 'employeeName',
            width: 200,
            render(text, record) {
                return (
                    <LinkTo
                        onClick={async (e, url) => {
                            // 埋点
                            await eventTrack({
                                eventName: 'personnel_management_onboardAndLeave_leave_resigned_detail_click',
                                eventProps: {
                                    label: '已离职员工-详情'
                                }
                            });
                            history.push(url);
                        }}
                        style={{
                            display: 'inline-block',
                            maxWidth: 200,
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap',
                            verticalAlign: ' text-bottom'
                        }}
                        className={styles.employeeName}
                        to="/office/personnelManagement/organization/employeeList/detail"
                        query={{
                            employeeCode: record.employeeCode
                        }}
                    >
                        {text}
                    </LinkTo>
                );
            }
        },
        {
            title: '所属公司',
            dataIndex: 'companyName',
            key: 'companyName',
            width: 200
        },
        {
            title: '部门',
            dataIndex: 'departmentName',
            key: 'departmentName',
            width: 200,
            render(text, record) {
                return <div>{record.departmentName}</div>;
            }
        },
        {
            title: '职位',
            dataIndex: 'postName',
            key: 'postName',
            width: 200,
            render(text, record) {
                return <div>{record.postName}</div>;
            }
        },
        {
            title: '实际离职日期',
            dataIndex: 'actualLeaveDate',
            key: 'actualLeaveDate',
            width: 150,
            render(text) {
                return <div>{moment(text).format('YYYY-MM-DD')}</div>;
            }
        },
        {
            title: '状态',
            dataIndex: 'states',
            key: 'states',
            render() {
                return <div className={styles.resignedDiv}>已离职</div>;
            }
        },
        {
            title: '操作',
            dataIndex: '',
            key: '',
            width: 100,
            fixed: 'right',
            render(text, record) {
                return (
                    <div>
                        <AuthComponent code="office:personnel:progress:leaveoffice:detail">
                            {record.id ? (
                                renderDetail(record)
                            ) : (
                                <span style={{ color: 'rgba(255,162,45,0.45)' }}>详情</span>
                            )}
                        </AuthComponent>
                    </div>
                );
            }
        }
    ];
    const resetForm = () => {
        eventTrack({
            eventName: 'personnel_management_onboardAndLeave_leave_resigned_reset_click',
            eventProps: {
                label: '已离职员工-重置'
            }
        });
        form.resetFields();
        history.push({
            query: {}
        });
    };
    // 分页功能
    const tableChange = paginations => {
        dispatch({
            type: 'resigned/save',
            payload: {
                pagination: {
                    ...resigned.pagination,
                    ...paginations
                }
            }
        });
    };

    // 每当分页数、页面条数、排序、筛查项改变时均应该重新请求表格数据
    useEffect(() => {
        fetchList();
    }, [pagination.pageSize, pagination.current]);

    useEffect(
        () => () => {
            form.resetFields();

            dispatch({
                type: 'resigned/save',
                payload: {
                    pagination: {
                        pageSize: 10,
                        current: 1,
                        total: 0
                    }
                }
            });
        },
        []
    );
    return (
        <PageHeaderWrapper>
            <PageRouter type="onboardAndLeave">
                <Card title="已离职员工" bordered={false}>
                    <Form
                        layout="inline"
                        style={{ marginBottom: 12 }}
                        onSubmit={e => {
                            e.preventDefault();
                            fetchList({ pageNo: 1 });
                        }}
                    >
                        <Form.Item label="员工姓名">
                            {getFieldDecorator('userName', {
                                initialValue: query.employeeName || ''
                            })(<Input style={{ width: 224 }} placeholder="请输入员工姓名" />)}
                        </Form.Item>
                        <Form.Item label="公司部门">
                            {getFieldDecorator('companyDepart', {
                                initialValue: {
                                    companyId: query.companyId,
                                    departmentId: query.departmentId
                                }
                                // 按钮权限暂未开发  先写死
                            })(<CompanyDepart />)}
                        </Form.Item>
                        <Form.Item label="离职日期">
                            {getFieldDecorator('changeDateSearch', {
                                initialValue: [
                                    query.startActualLeaveDate ? moment(query.startActualLeaveDate) : '',
                                    query.endActualLeaveDate ? moment(query.endActualLeaveDate) : ''
                                ]
                            })(<RangePicker format="YYYY-MM-DD" placeholder={['开始日期', '结束日期']} />)}
                        </Form.Item>
                        <Form.Item>
                            <Button
                                type="primary"
                                // 埋点
                                onClick={() => {
                                    eventTrack({
                                        eventName: 'personnel_management_onboardAndLeave_leave_resigned_search_click',
                                        eventProps: {
                                            label: '已离职员工-查询',
                                            key_words: JSON.stringify(getFieldsValue())
                                        }
                                    });
                                    history.push({
                                        query: {
                                            ...query,
                                            ...getSearchData()
                                        }
                                    });
                                    fetchList({ pageNo: 1 });
                                }}
                            >
                                查询
                            </Button>
                        </Form.Item>
                        <Form.Item>
                            <Button htmlType="submit" onClick={resetForm}>
                                重置
                            </Button>
                        </Form.Item>
                    </Form>
                    <div>
                        <Table
                            bordered={false}
                            columns={columns}
                            scroll={{
                                x: 'max-content'
                            }}
                            dataSource={data}
                            rowKey="employeeId"
                            onChange={tableChange}
                            loading={loading.models.resigned}
                            pagination={false}
                        />
                        <Pagination {...pagination} onChange={tableChange} />
                    </div>
                </Card>
            </PageRouter>
        </PageHeaderWrapper>
    );
};
export default connect(({ resigned, loading }) => ({
    resigned,
    loading
}))(Form.create()(Resigned));
